<?php
/**
 * Created by PhpStorm.
 * User: LG
 * Date: 2017/9/21
 * Time: 16:07
 */

namespace app\administrative\controller;

use app\common\model\Contract;
use app\common\model\Customer;
use app\common\model\Administrative;
use app\common\model\Engineers;
use app\common\model\Equipments;
use app\common\model\ContractEquipment;
use app\common\model\Operation;
use app\common\model\Parts;
use app\common\model\Configuration;
use think\Cache;
use think\Db;
use think\Exception;
use think\Request;

/*
 *  行政区域--->合同
 */

class Contractinfo extends Base
{
    protected $Contract;
    protected $Operation;
    protected $User;
    public function __construct()
    {
//        return $this->error('系统维护中，请稍后！');
        parent::__construct();
        $this->Contract = new Contract('administrative_user','administrative_log');
        $this->User = new Administrative();
        $this->Operation = new Operation();
    }

    /*
     *  合同列表
     */
    public function index()
    {
        $whereArray = input('');
        $where = [];
        foreach ($whereArray as $kw => $vw){
            if (empty($vw)){
                continue;
            }
            if ($kw == 'username'){
                $where['rq_customer.'.$kw] = ['like','%'.$vw.'%'];
                continue;
            }
            if ($kw == 'id_card'){
                $where['rq_customer.'.$kw] = $vw;
                continue;
            }
            if ($kw == 'address'){
                $where['rq_contract.'.$kw] = ['like','%'.$vw.'%'];
                continue;
            }
            $where[$kw] = $vw;
        }
        $uid = session($this->set['db_name'].'uid');
        $a_id = $this->User->findUserInfo(['id'=>$uid],[],'a_id');
        $where = array_merge($where,$a_id);
        $where['rq_contract.administrative_id'] = $a_id['a_id'];
        //获取数据
        $data = $this->Contract->selectPage($where);

        $EquipmentNumberWhere = [
            'is_delete'=>0,
            'state'=>1
        ];
        foreach ($data['data'] as $key => $value){
            //获取设备台数
            $EquipmentNumberWhere['contract_id'] = $value['contract_id'];
            $EquipmentNumberWhere['state'] = 1;
            $EquipmentNumberWhere['is_delete'] = 0;
            $data['data'][$key]['EquipmentNumber'] = $this->Contract->getEquipmentNumber($EquipmentNumberWhere);
        }

        $this->assign('Nowpage', $data['page']['currentPage']); //当前页
        $this->assign('allpage', $data['page']['lastPage']); //总页数
        $this->assign('count', $data['page']['count']);//总条数
        $this->assign('data',$data['data']);
        if(input('get.page')){
            return json($data);
        }

        return $this->fetch('contract/contract');
    }

    /**
     * 合同详情
     * @author ligang
     * @Request contract_id             int    GET   合同ID
     * @return array
     */
    public function details()
    {
        //检验get参数
        if (input('?get.contract_id')){
            //获取参数并强制转换为int型
            $contract_id = input('get.contract_id');
        }else{
            return json(array('code'=>0,'msg'=>'缺少必要参数'));
        }
        $join = [
            ['rq_customer','rq_contract.user_id = rq_customer.user_id'],
            ['rq_contract_remark','rq_contract_remark.contract_no = rq_contract.contract_no','LEFT']
        ];
        $field = '
            rq_customer.employee_id,
            rq_customer.username,
            rq_customer.telphone,
            rq_customer.add_time,
            rq_customer.account_status,
            rq_customer.remark,
            rq_customer.user_address,
            rq_customer.user_type,
            rq_customer.province,
            rq_customer.city,
            rq_customer.area,
            rq_customer.birthday,
            rq_contract.contract_no,
            rq_contract.contract_id,
            rq_contract.introducer_id,
            rq_contract.applicant,
            rq_contract.receipt,
            rq_contract.water_pressure,
            rq_contract.contract_money,
            rq_contract.nature,
            rq_contract.contract_type,
            rq_contract.province as ht_province,
            rq_contract.city as ht_city,
            rq_contract.area as ht_area,
            rq_contract.address,
            rq_contract.original_parts,
            rq_contract.installed_time,
            rq_contract.recent_time,
            rq_contract.for_core_cost,
            rq_contract.for_core_cycle,
            rq_contract.for_core_time,
            rq_contract.moving_machine_number,
            rq_contract.renew_date,
            rq_contract.for_core_number,
            rq_contract.administrative_id,
            rq_contract.corporate_name,
            rq_contract.housing_property,
            rq_contract.exire_date,
            rq_contract_remark.remark as contract_remark,
            rq_customer.is_entry
            ';
        //获取数据
        $data = $this->Contract->details(['contract_id'=>$contract_id],$join,$field);

        //转换客户状态
        foreach ($data as $key => $value){
            if ($key == 'account_status'){
                if ($value == 1){
                    $data[$key] = "正常";
                }else{
                    $data[$key] = "冻结";
                }
                continue;
            }if ($key == 'contract_type'){
                if ($value == 0){
                    $data[$key] = "未升级VIP";
                }else{
                    $data[$key] = "已升级VIP";
                }
                continue;
            }if ($key == 'user_type'){
                if ($value == 1){
                    $data[$key] = "普通用户";
                }else{
                    $data[$key] = "VIP用户";
                }
                continue;
            }
            if ($key == 'exire_date'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'add_time'){
                $data[$key] = date('Y-m-d H:i:s',$value);
                continue;
            }
            if ($key == 'birthday'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'installed_time'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'recent_time'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'for_core_time'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'renew_date'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'housing_property'){
                if ($value == 1){
                    $data[$key] = "公租房";
                }elseif ($value == 2){
                    $data[$key] = "廉租房";
                }elseif ($value == 3){
                    $data[$key] = "租赁";
                }else{
                    $data[$key] = "购买";
                }
                continue;
            }
            if ($key == 'nature'){
                //1.商用客户,2.家用客户,3外接包年,4.外接点餐,5.购买客户
                if ($value == 1){
                    $data[$key] = "商用客户";
                }elseif ($value == 2){
                    $data[$key] = "家用客户";
                }elseif ($value == 3){
                    $data[$key] = "外接包年";
                }elseif ($value == 4){
                    $data[$key] = "外接点餐";
                }else{
                    $data[$key] = "购买客户";
                }
                continue;
            }
        }
        //判断是否是员工
        if ($data['is_entry'] == 1){
            $data['is_entry'] = "是";
            $data['personnel_number'] = $data['employee_id'];
        }else{
            $data['is_entry'] = "否";
            $data['personnel_number'] = "";
        }

        //获取转介绍人
        $Customer = new Customer();
        $data['introducer_id'] = $Customer->selectOne(['user_id'=>$data['introducer_id']])[0]['username'];
        $data['applicant'] = $Customer->selectOne(['user_id'=>$data['applicant']])[0]['username'];

        //获取设备台数
        $data['EquipmentNumber'] = $this->Contract->getEquipmentNumber(['contract_id'=>$contract_id,'state'=>1,'rq_contract_equipment.is_delete'=>0]);
        //获取设备记录
        $Equipment_join = [
            ['rq_equipments','rq_contract_equipment.equipments_id = rq_equipments.equipments_id'],
        ];
        //查询设备字段
        $Equipment_field = 'rq_equipments.equipments_name,
                            rq_contract_equipment.id,
                            rq_contract_equipment.equipments_id,
                            rq_contract_equipment.equipments_number,
                            rq_contract_equipment.equipments_address,
                            rq_contract_equipment.moving_machine_number
                            ';
        $data['equipment'] = $this->Contract->contractEquipment(['contract_id'=>$contract_id,'state'=>1,'rq_contract_equipment.is_delete'=>0],$Equipment_join,$Equipment_field);
        $newArr = [];
        foreach ($data['equipment'] as $key => $value){
            $data['equipment'][$key]['Remark'] = $this->Contract->equipmentsRemark(['contract_equipment_id'=>$value['id']]);
            for($i=1;$i<=8;$i++){
                if ($i == 1 || $i == 6){
                    continue;
                }
                $record = $this->Contract->equipmentRecord($i,['equipment_id'=>$value['id']]);
                if ($record){
                    foreach ($record as $rk => $rv){
                        switch ($i){
                            case 1:
                                $type = "新装";
                                break;
                            case 2:
                                $type = "维修";
                                break;
                            case 3:
                                $type = "换芯";
                                break;
                            case 4:
                                $type = "拆机";
                                break;
                            case 5:
                                $type = "移机";
                                break;
                            case 6:
                                $type = "续费";
                                break;
                            case 7:
                                $type = "换芯+维修";
                                break;
                            case 8:
                                $type = "续费+维修";
                                break;
                            default:
                                $type = "未知类型";
                        }
                        $record[$rk]['type'] = $type;
                        $data['equipment'][$key]['record'][] = $record[$rk];
                    }
                }
            }
        }
//        dump($data);
        //合同操作记录
        $ContractLogWhere['contract_id'] = $contract_id;
        $ContractLog = $this->Contract->getContractLog($ContractLogWhere,[],'');
        foreach ($ContractLog as $clk=>$clv){
            $ContractLog[$clk]['do_time'] = date('Y-m-d H:i:s',$clv['do_time']);
            switch ($clv['do_type']){
                case 1:
                    $ContractLog[$clk]['do_type'] = "新增";
                    break;
                case 2:
                    $ContractLog[$clk]['do_type'] = "删除";
                    break;
                case 3:
                    $ContractLog[$clk]['do_type'] = "修改";
                    break;
                case 4:
                    $ContractLog[$clk]['do_type'] = "解绑";
                    break;
            }
        }
        //判断是哪个端的
        foreach ($ContractLog as $key => $value){
            switch ($value['terminal_type']){
                //总后台
                case 0:
                    if ($value['do_id'] == 0){
                        $ContractLog[$key]['name'] = '系统';
                        $ContractLog[$key]['title'] = '系统';
                        break;
                    }
                    $findUserJoin = [
                        ['rq_admin_auth_group','rq_admin_user.groupid = rq_admin_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_admin_user.id'=>$value['do_id']
                    ];
                    $findUserField = 'rq_admin_user.name,rq_admin_auth_group.title';
                    $admin_user = $this->Contract->findUser('admin_user',$findUserWhere,$findUserJoin,$findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                 //行政区域
                case 1:
                    $findUserJoin = [
                        ['rq_administrative_auth_group','rq_administrative_user.groupid = rq_administrative_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_administrative_user.id'=>$value['do_id']
                    ];
                    $findUserField = 'rq_administrative_user.name,rq_administrative_auth_group.title';
                    $admin_user = $this->Contract->findUser('administrative_user',$findUserWhere,$findUserJoin,$findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                //运营中心
                case 2:
                    $findUserJoin = [
                        ['rq_operation_auth_group','rq_operation_user.groupid = rq_operation_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_operation_user.id'=>$value['do_id']
                    ];
                    $findUserField = 'rq_operation_user.name,rq_operation_auth_group.title';
                    $admin_user = $this->Contract->findUser('operation_user',$findUserWhere,$findUserJoin,$findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
            }
        }
        //获取合同原始配件
        $PartsObj = new Parts();
        $PartsWhere = [
            'contract_id'=>$contract_id,
            'is_original'=>1,
            'rq_equipments_parts.is_delete'=>0
        ];
        $PartsJoin = [
            ['rq_parts','rq_equipments_parts.parts_id = rq_parts.parts_id']
        ];
        $PartsField = 'parts_name,parts_number';
        $Parts = $PartsObj->getContractParts($PartsWhere,$PartsField,$PartsJoin);
        //追加原始配件
        $data['original_parts'] = $Parts;
        //获取设备名称（型号）
        $equipmentsObj = new Equipments();
        $Equipments_name = $equipmentsObj->getList();
        //追加合同操作记录
        $data['ContractLog'] = $ContractLog;
        //模板赋值
        $this->assign('data',$data);
        $this->assign('Equipments_name',$Equipments_name);
        //渲染模板
        return $this->fetch("contract/details");
    }

    /*
     *  获取设备操作记录
     *  @author 李港
     *  @param int  $id                     合同设备关联ID
     *  @param int  $equipments_number      设备编号
     *  @param int  $page                   页数
     *  @return array|json
     */
    public function getEquipmentRecord()
    {
        //获取合同设备关联ID
        $id = input('?get.id')?input('get.id'):false;
        $equipments_number = input('?get.equipments_number')?input('get.equipments_number'):false;
        $page = input('?get.page')?input('get.page'):1;
        if (!$id || !$equipments_number){
            return ['code'=>0,'msg'=>'缺少必要参数'];
        }
        $recordData = [];
        for($i=1;$i<=8;$i++){
            $record = $this->Contract->equipmentRecord($i,['equipment_id'=>$id]);
            if ($record){
                foreach ($record as $rk => $rv){
                    switch ($i){
                        case 1:
                            $type = "新装";
                            break;
                        case 2:
                            $type = "维修";
                            break;
                        case 3:
                            $type = "换芯";
                            break;
                        case 4:
                            $type = "拆机";
                            break;
                        case 5:
                            $type = "移机";
                            break;
                        case 6:
                            $type = "续费";
                            break;
                        case 7:
                            $type = "换芯+维修";
                            break;
                        case 8:
                            $type = "续费+维修";
                            break;
                        default:
                            $type = "未知类型";
                    }
                    $record[$rk]['type'] = $type;
                    $recordData[] = $record[$rk];
                }
            }
        }
        $Engineer = new Engineers();
        $ContractEquipment = new ContractEquipment();
        $EngineerField = 'engineers_name';
        $EquipmentsField = 'equipments_address';
        foreach ($recordData as $key => $value){
            $recordData[$key]['equipments_number'] = $equipments_number;
            //操作人
            if ($value['repair_id'] == 0){
                $recordData[$key]['repair_id'] = '系统';
            }else{
                $recordData[$key]['repair_id'] = $Engineer->getEngineerInfo(['engineers_id'=>$value['repair_id']],$EngineerField)['engineers_name'];
            }
            //设备地址
            $recordData[$key]['address'] = $ContractEquipment->findEquipmentsData(['id'=>$id],[],$EquipmentsField)['equipments_address'];
            //操作时间
            foreach (array_keys($recordData[$key]) as $k=>$v){
                if (strpos($v,'time')){
                    $recordData[$key]['do_date'] = date('Y-m-d H:i:s',$value[$v]);
                    unset($recordData[$key][$v]);
                    continue;
                }
            }
        }
        $Configuration = new Configuration();
        //每页显示数目
        $listRows = intval($Configuration->getkey('pagesize'));
        //总条数
        $recordTotal = count($recordData);
        //总页数
        $recordTotalPage = ceil($recordTotal / $listRows);
        if ($page == 1){
            $start = 0;
        }else{
            $start = ($page - 1) * $listRows;
        }
        $data = array_slice($recordData,$start,$listRows);
        $data['data'] = $data;
        $data['page']['currentPage'] = $page;
        $data['page']['lastPage'] = $recordTotalPage;
        $data['page']['count'] = $recordTotal;
        if (input('?get.page')){
            return json($data);
        }
    }

    /*
     *  获取合同图片
     *  @author ligang
     *  @Request contract_id             int    GET   合同ID
     *  @return array
     */
    public function contractImages()
        {
            $id = input('?get.id')?input('get.id'):false;
            if (!$id){
                return ['code'=>0,'msg'=>'非法请求'];
            }
            $data = $this->Contract->contractImg(['contract_id'=>$id],'contract_imgs');
            if (is_null(json_decode($data['contract_imgs']))){
                return ['code'=>0,'msg'=>'数据格式错误'];
            }
            $imgUrl = json_decode($data['contract_imgs']);
            $array = [
                'code'=>1,
                'data'=>$imgUrl
            ];
            return  json($array);
        }

    /*
     *  获取合同操作记录
     */
    public function getAllContractLog()
        {
            $contract_id = input('?get.contract_id')?input('get.contract_id/d'):false;
            if (!$contract_id){
                return ['code'=>0,'msg'=>'缺少必要参数'];
            }
            $ContractLogWhere['contract_id'] = $contract_id;
            $page =1;
            $page_number = '';
            $ContractLog = $this->Contract->getContractLog($ContractLogWhere,[],'',$page,$page_number);
            foreach ($ContractLog as $clk=>$clv){
                $ContractLog[$clk]['do_time'] = date('Y-m-d H:i:s',$clv['do_time']);
                switch ($clv['do_type']){
                    case 1:
                        $ContractLog[$clk]['do_type'] = "新增";
                        break;
                    case 2:
                        $ContractLog[$clk]['do_type'] = "删除";
                        break;
                    case 3:
                        $ContractLog[$clk]['do_type'] = "修改";
                        break;
                    case 4:
                        $ContractLog[$clk]['do_type'] = "解绑";
                        break;
                }
            }
            foreach ($ContractLog as $key => $value){
                switch ($value['terminal_type']){
                    //总后台
                    case 0:
                        if ($value['do_id'] == 0){
                            $ContractLog[$key]['name'] = '系统';
                            $ContractLog[$key]['title'] = '系统';
                            break;
                        }
                        $findUserJoin = [
                            ['rq_admin_auth_group','rq_admin_user.groupid = rq_admin_auth_group.id']
                        ];
                        $findUserWhere = [
                            'rq_admin_user.id'=>$value['do_id']
                        ];
                        $findUserField = 'rq_admin_user.name,rq_admin_auth_group.title';
                        $admin_user = $this->Contract->findUser('admin_user',$findUserWhere,$findUserJoin,$findUserField);
                        $ContractLog[$key]['name'] = $admin_user['name'];
                        $ContractLog[$key]['title'] = $admin_user['title'];
                        break;
                    //行政区域
                    case 1:
                        $findUserJoin = [
                            ['rq_administrative_auth_group','rq_administrative_user.groupid = rq_administrative_auth_group.id']
                        ];
                        $findUserWhere = [
                            'rq_administrative_user.id'=>$value['do_id']
                        ];
                        $findUserField = 'rq_administrative_user.name,rq_administrative_auth_group.title';
                        $admin_user = $this->Contract->findUser('administrative_user',$findUserWhere,$findUserJoin,$findUserField);
                        $ContractLog[$key]['name'] = $admin_user['name'];
                        $ContractLog[$key]['title'] = $admin_user['title'];
                        break;
                    //运营中心
                    case 2:
                    $findUserJoin = [
                        ['rq_operation_auth_group','rq_operation_user.groupid = rq_operation_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_operation_user.id'=>$value['do_id']
                    ];
                    $findUserField = 'rq_operation_user.name,rq_operation_auth_group.title';
                    $admin_user = $this->Contract->findUser('operation_user',$findUserWhere,$findUserJoin,$findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                }
            }
            $data['code'] = 1;
            $data['data'] = $ContractLog;
            return json($data);
        }

    /*
     * 添加设备备注
     * @author ligang
     * @Request equipments_id             int    GET   设备ID
     */
    public function addRemark()
    {
        $id = input('?get.id')?input('get.id'):false;
        if (!$id){
            return ['code'=>0,'msg'=>'缺少必要参数'];
        }
        $contract_id = input('?get.contract_id')?input('get.contract_id'):false;
        if (!$contract_id){
            return ['code'=>0,'msg'=>'缺少必要参数'];
        }
        $equipments_id = input('?get.equipments_id')?input('get.equipments_id'):false;
        if (!$equipments_id){
            return ['code'=>0,'msg'=>'缺少必要参数'];
        }
        $remark = input('?get.remark')?input('get.remark'):false;
        if (!$remark){
            return ['code'=>0,'msg'=>'请输入备注信息'];
        }
        //组装数据
        $data['contract_equipment_id'] = $id;
        $data['equipments_remark'] = trim($remark);
        $Equipments_add = $this->Contract->addEquipmentsRemark($data);
        //添加合同操作记录
        $where['id'] = $id;
        $Equipment = $this->Contract->contractEquipment($where,[],'equipments_number')[0];
        $Log = [
            'contract_id'=>$contract_id,
            'do_type'=>1,
            'terminal_type'=>2,
            'new_value'=>$Equipment['equipments_number']."设备备注：".$remark,
        ];
        if ($Equipments_add){
            $this->Contract->addContractLog($Log);
            return ['code'=>1,'msg'=>'添加成功'];
        }else{
            return ['code'=>0,'msg'=>'添加失败'];
        }
    }

    /*
     * 修改设备
     * @author ligang
     * @Request equipments_id             int    GET   设备ID
     */
    public function editEquipments()
    {
        $id = input('?get.id')?input('get.id'):false;
        $equipments_id = input('?get.equipments_id')?input('get.equipments_id'):false;
        $contract_id = input('?get.contract_id')?input('get.contract_id'):false;
        $equipments_name = input('?get.equipments_name')?trim(input('get.equipments_name')):false;
        $equipments_number = !empty(input('param.equipments_number'))?trim(input('param.equipments_number')):false;

        if (!$equipments_id || !$contract_id || !$id){
            return ['code'=>0,'msg'=>'缺少必要参数'];
        }
        if (!$equipments_name){
            return ['code'=>0,'msg'=>'请输入设备型号'];
        }
        if (!$equipments_number){
            return ['code'=>0,'msg'=>'请输入设备编号'];
        }
        if (strlen($equipments_number) != 10){
            return ['code'=>0,'msg'=>'设备编号为10位纯数字'];
        }
        $ContractEquipmentObj = new ContractEquipment();
        $EquipmentObj = new Equipments();
        $checkNumber = $ContractEquipmentObj->getEquipmentsData(['equipments_number'=>$equipments_number]);
        if ($checkNumber){
            return ['code'=>0,'msg'=>'设备编号已存在'];
        }
        $where['id'] = $id;
        $join = [
            ['rq_equipments','rq_contract_equipment.equipments_id = rq_equipments.equipments_id']
        ];
        $equipments = $ContractEquipmentObj->getEquipmentsData($where,$join,'equipments_name,rq_contract_equipment.equipments_number')[0];
        $newWhere = [
            'equipments_id'=>$equipments_name
        ];
        $newEquipmentsName = $EquipmentObj->selectOne($newWhere);
        $updateData['id'] = $id;
        $updateData['equipments_id'] = $equipments_name;
        $updateData['equipments_number'] = $equipments_number;
        $updateData['uptime'] = time();
        $result = $ContractEquipmentObj->updateEquipmentsData([],$updateData);
        if ($result){
            $data['old_value'] = '设备ID:'.$equipments['equipments_name'].';'.'设备编号:'.$equipments['equipments_number'];
            $data['new_value'] = '设备ID:'.$newEquipmentsName['equipments_name'].';'.'设备编号:'.$updateData['equipments_number'];
            $data['contract_id'] = $contract_id;
            $data['do_type'] = 3;
            $data['terminal_type'] = 1;
            $this->Contract->addContractLog($data);
            return ['code'=>1,'msg'=>'修改成功'];
        }else{
            return ['code'=>0,'msg'=>'修改失败'];
        }
    }

    /*
     * 解绑设备
     * @author ligang
     * @Request equipments_id             int    GET   合同设备ID
     */
    public function unBindEquipments($e_id = '')
    {
        $id = empty($e_id)?input('get.id'):$e_id;
        $ContractEquipmentObj = new ContractEquipment();
        $EquipmentsInfo = $ContractEquipmentObj->getEquipmentsData(['id'=>$id])[0];
        if ($EquipmentsInfo){
            $result = $ContractEquipmentObj->edit(['id'=>$id],['state'=>0]);
            if ($result){

                $Log = [
                    'contract_id'=>$EquipmentsInfo['contract_id'],
                    'do_type'=>4,
                    'terminal_type'=>1,
                    'old_value'=>'设备编号：'.$EquipmentsInfo['equipments_number'],
                    'new_value'=>''
                ];
                $this->Contract->addContractLog($Log);

                //判断合同下是否存在设备
                $ContractEquipmentDataWhere = [
                    'contract_id'=>$EquipmentsInfo['contract_id'],
                    'state'=>1,
                    'is_delete'=>0,
                ];
                $ContractEquipmentData = $ContractEquipmentObj->getEquipmentsData($ContractEquipmentDataWhere);
                if (empty($ContractEquipmentData)){
                    $Contract = new Contract();
                    $ContractWhere = [
                        'contract_id'=>$EquipmentsInfo['contract_id']
                    ];
                    $ContractData = [
                        'contract_status'=>7,
                        'update_time'=>time()
                    ];
                    $Contract->updateContract($ContractWhere,$ContractData);
                    $ContractLog = [
                        'contract_id'=>$EquipmentsInfo['contract_id'],
                        'do_type'=>3,
                        'terminal_type'=>1,
                        'old_value'=>'',
                        'new_value'=>'合同下不存在设备，改为无效合同'
                    ];
                    $this->Contract->addContractLog($ContractLog);
                }
                return ['code'=>1,'msg'=>'解绑成功'];
            }else{
                return ['code'=>0,'msg'=>'解绑失败'];
            }
        }else{
            return ['code'=>0,'msg'=>'设备不存在'];
        }

    }

    /*
     *  添加合同
     *  @author ligang
     */
    public function addContract()
    {
        $Operation = new Operation();
        //读取配置
        $Configuration = new Configuration();
        $hxcycle = json_decode($Configuration->getkey('defaultinfo'));
        $this->assign('hxcycle',$hxcycle->hxcycle);
        $this->assign('xfcycle',$hxcycle->xfcycle);

        //配件
        $PartsObj = new Parts();
        $Parts = $PartsObj->getList();
        //设备型号
        $Equipments = new Equipments();
        $equipments_name = $Equipments->getList();
        //客户性质
        $nature = config('nature');
        //显示公司名称
        $is_nature = config('is_nature');
        //住房性质
        $housing_property = config('housing_property');
        //状态
        $contract_status = config('contract_status');
        //当前行政区域ID
        $a_id = session($this->set['db_name'].'a_id');
        $AdministrativeInfo = $Operation->findAdministrative(['a_id'=>$a_id]);
        if (strpos($AdministrativeInfo['area_id'],',')){
            $areaArray = explode(',',$AdministrativeInfo['area_id']);
            $AdministrativeInfo['area_id'] = $areaArray[0];
        }
        $this->assign('AdministrativeInfo',$AdministrativeInfo);
        //Operation
        $Province = $Operation->areasProvince();
        $this->assign('Province',$Province);
        $data = [
            'nature'=>$nature,
            'is_nature'=>$is_nature,
            'housing_property'=>$housing_property,
            'equipments_name'=>$equipments_name,
            'Parts'=>$Parts,
            'contract_status'=>$contract_status
        ];
        $this->assign('select',$data);
        return  $this->fetch('contract/AddContract');
    }

    /**
     * 通过员工编号获取姓名
     * @author ligang
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @date 2018/9/5 11:32
     */
    public function getWorker()
    {
        $number = input('post.number');
        $result = Db::table('rq_customer')->where(['employee_id'=>$number])->field('username')->find();
        $data = [
            'code'=>1000,
            'msg'=>'',
            'data'=>isset($result['username']) ? $result['username'] : '未找到申请人'
        ];
        return json($data);
    }

    /**
     * 通过合同编号获取客户姓名
     * @author ligang
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @date 2018/9/5 11:42
     */
    public function getUsername()
    {
        $number = input('post.number');
        $join = [
            ['rq_customer','rq_contract.user_id = rq_customer.user_id','LEFT']
        ];
        $result = Db::table('rq_contract')->join($join)->where(['contract_no'=>$number])->field('username')->find();
        $data = [
            'code'=>1000,
            'msg'=>'',
            'data'=>isset($result['username']) ? $result['username'] : '未找到合同客户'
        ];
        return json($data);
    }

    /*
     *  操作添加合同
     *  @author 李港
     */
    public function doAddContract()
    {
        //实例化合同设备关联model
        $ContractEquipmentObj = new ContractEquipment();
        $PartsObj = new Parts();
        $data = $this->request->post();

        foreach ($data as $key => $value){
            if ($key == 'renew_date'){
                continue;
            }
            //转化时间
            if (strpos($key,'time') || strpos($key,'date')){
                if (!empty($value)){
                    $data[$key] = strtotime($value);
                    continue;
                }
            }

            //去掉空格
            if (!is_array($value)){
                $data[$key] = trim($value);
                continue;
            }
        }
        if(isset($data['contract_no'])){
            //检查合同编号是否唯一
            $checkContract_no = $this->Contract->selectOne(['contract_no'=>$data['contract_no']]);
            if ($checkContract_no){
                return  ['code'=>0,'msg'=>'合同编号已存在'];
            }
        }
//        return json(['code'=>0,'msg'=>'紧急维护中，大于10分钟','data'=>$checkContract_no]);
        //检查收据编号是否唯一
        $checkContract_no = $this->Contract->selectOne(['receipt'=>$data['receipt']]);
        if ($checkContract_no){
            return  ['code'=>0,'msg'=>'收据编号已存在'];
        }
        //检查是否为空
        $msg = '';
        foreach ($data as $emk=>$emv){
            //判断基本信息
            if (!is_array($emv)){
                if (strlen($emv) == 0){
                    switch ($emk){
                        case 'user_id':
                            $msg = '用户';
                            break;
                        case 'contract_money':
                            $msg = '合同金额';
                            break;
                        case 'contact_person':
                            $msg = '联系人';
                            break;
                        case 'installed_time':
                            $msg = '装机时间';
                            break;
                        case 'phone':
                            $msg = '联系电话';
                            break;
                        case 'renew_date':
                            $msg = '续费周期';
                            break;
                        case 'for_core_cycle':
                            $msg = '换芯周期';
                            break;
                        case 'nature':
                            $msg = '客户性质';
                            break;
                        case 'housing_property':
                            $msg = '住房性质';
                            break;
                        case 'recent_time':
                            $msg = '最近一次换芯时间';
                            break;
                        case 'for_core_time':
                            $msg = '换芯时间';
                            break;
                        case 'for_core_cost':
                            $msg = '服务金额';
                            break;
                        case 'for_core_number':
                            $msg = '免费换芯次数';
                            break;
                        case 'moving_machine_number':
                            $msg = '用户';
                            break;
                        case 'exire_date':
                            $msg = '到期时间';
                            break;
                        case 'contract_status':
                            $msg = '账户状态';
                            break;
                        case 'province_code':
                            $msg = '省';
                            break;
                        case 'city_code':
                            $msg = '市';
                            break;
                        case 'area_code':
                            $msg = '区/县';
                            break;
                        case 'address':
                            $msg = '详细地址';
                            break;
                        case 'applicant':
                            $msg = '申请人';
                            break;
                        case 'receipt':
                            $msg = '收据编号';
                            break;
                        case 'water_pressure':
                            $msg = '水压';
                            break;
                        case 'eq_count':
                            $msg = '合同折合台数';
                            break;
                    }
                }
            }else{
                //判断设备编号
                if ($emk == 'equipments_number'){
                    foreach ($emv as $cheqk=>$cheqv){
                        if (empty($cheqv)){
                            $msg = '设备编号';
                            break;
                        }
                    }
                }
                //判断设备型号
                if ($emk == 'equipments_name'){
                    foreach ($emv as $cheqk=>$cheqv){
                        if (empty($cheqv)){
                            $msg = '设备型号';
                            break;
                        }
                    }
                }
                //判断配件数量
                if ($emk == 'parts_number'){
                    foreach ($emv as $cheqk=>$cheqv){
                        if (empty($cheqv)){
                            $msg = '配件数量';
                            break;
                        }
                    }
                }
            }
        }
        if (!empty($msg)){
            return ['code'=>0,'msg'=>$msg.'不能为空'];
        }

        //组装配件数据
        $parts = [];
        foreach ($data['parts_id'] as $pk=>$pv){
            if (empty($pv)){
                return ['code'=>0,'msg'=>'请选择原始配件'];
            }
            foreach ($data['parts_number'] as $pnk=>$pnv){
                if (empty($pnv)){
                    return ['code'=>0,'msg'=>'请输入原始配件数量'];
                }
                if ($pk == $pnk){
                    $parts[$pk]['parts_id'] = $pv;
                    $parts[$pk]['parts_number'] = $pnv;
                    $parts[$pk]['contract_id'] = '';//合同添加成功返回合同ID
                    $parts[$pk]['is_original'] = 1;
                }

            }
        }
        unset($data['parts_id']);
        unset($data['parts_number']);
        //组装设备数据
        $equipments = [];
        foreach ($data['equipments_number'] as $numberK=>$numberV){
            if (empty($numberV)){
                return ['code'=>0,'msg'=>'请输入设备编号'];
            }
            $checkEquipmentsNumber = $ContractEquipmentObj->getEquipmentsData(['equipments_number'=>$numberV,'state'=>1]);
            if ($checkEquipmentsNumber){
                return ['code'=>0,'msg'=>'设备编号已存在，请重新选择设备编号'];
            }
            foreach ($data['equipments_name'] as $nameK=>$nameV){
                if (empty($nameV)){
                    return ['code'=>0,'msg'=>'请输入设备型号'];
                }
                if ($numberK == $nameK){
                    $equipments[$nameK]['equipments_number'] = $numberV;
                    $equipments[$nameK]['equipments_id'] = $nameV;
                    $equipments[$nameK]['equipments_address'] = $data['address'];
                    $equipments[$nameK]['moving_machine_number'] = $data['moving_machine_number'][$nameK]?$data['moving_machine_number'][$nameK]:1;
                    $equipments[$nameK]['addtime'] = time();
                    $equipments[$nameK]['uptime'] = time();
                }
            }
        }
        if (!isset($data['contract_imgs']) && empty($data['contract_imgs'])){
            return ['code'=>0,'msg'=>'请上传图片'];
        }
        $data['contract_imgs'] = json_encode($data['contract_imgs']);
		
        //去掉合同中的设备信息
        unset($data['equipments_number']);
		unset($data['equipments_name']);
        

        $data['moving_machine_number'] = $data['contract_moving_machine_number'];
        unset($data['contract_moving_machine_number']);

        //获取省市区
        $data['province'] = $this->Operation->findAddrName(['id'=>$data['province_code']])[0]['area_name'];
        $data['city'] = $this->Operation->findAddrName(['id'=>$data['city_code']])[0]['area_name'];
        $data['area'] = $this->Operation->findAddrName(['id'=>$data['area_code']])[0]['area_name'];
        //获取运营中心/行政区域ID
        $a_id = session($this->set['db_name'].'a_id');
        $o_id = $this->Operation->findAdministrative(['a_id'=>$a_id])['operation'];
        $data['administrative_id'] = $a_id;
        $data['operation_id'] = $o_id;
        $data['add_time'] = time();
        //合同备注
        $remark['remark'] = $data['remark'];
        $remark['add_time'] = time();
        $remark['contract_no'] = $data['contract_no'];

        unset($data['engineers_name']);
        unset($data['remark']);

        //区分手动输入（绑定设备）和自动生成（新增设备）
        //手动输入必须是已经解绑的设备
        foreach ($data['is_AI'] as $AIKey=>$AIValue){
            if ($AIValue == 'no'){
                $checkEquipmentNumberWhere = [
                    'equipments_number'=>$equipments[$AIKey]['equipments_number'],
                    'state'=>0,
                    'is_delete'=>0
                ];
                $checkEquipmentNumber = $ContractEquipmentObj->findEquipmentsData($checkEquipmentNumberWhere);
                if(!$checkEquipmentNumber){
                    return json(['code'=>0,'msg'=>'手动输入的设备编号有误']);
                }
            }
        }
        unset($data['is_AI']);


        //转介绍人
        $Customer = new Customer();
        if(!empty($data['customer_introducer_name'])) {
            $introducer = $data['customer_introducer_name'];
            $res = db('contract')->where('contract_no', $introducer)->find();
            if ($res) {
                $data['introducer_id'] = $res['user_id'];
            } else {
                return ['code' => 0, 'msg' => '转介绍人合同不存在'];
            }
        }

//        if (!empty($introducer)){
//            $introducer_user = $Customer->findOne(['rq_customer.telphone'=>$introducer]);
//            if ($introducer_user){
//                if ($introducer_user['is_entry'] == 1){
//                    return ['code'=>0,'msg'=>'转介绍人不能为员工'];
//                }
//                $introducer_id = $introducer_user['user_id'];
//            }else{
//                return ['code'=>0,'msg'=>'请输入有效的转介绍人电话'];
//            }
////            if ($introducer_id == $data['user_id']){
////                return ['code'=>0,'msg'=>'转介绍人不能是用户'];
////            }
//            //假如该用户存在合同，则合同转介绍人必须一致
//            if (empty($data['user_id'])){
//                return ['code'=>0,'msg'=>'请选择合同用户'];
//            }else{
//                $ContractInfo = $this->Contract->findUser('contract',['user_id'=>$data['user_id']]);
//                if (!empty($ContractInfo)){
//                    if ($ContractInfo['introducer_id'] != $introducer_user['user_id']){
//                        $introducerInfo = $this->Contract->findUser('customer',['user_id'=>$ContractInfo['introducer_id']]);
//                        return ['code'=>3,'msg'=>'您已存在其他合同，合同转介绍人必须和其他合同一致,您的转介绍人电话为：'.$introducerInfo['telphone']];
//                    }
//                }
//            }
//            $data['introducer_id'] = $introducer_id;
//
//            //转介绍人信息
////            $introducer_info = $Customer->selectOne(['user_id'=>$introducer_id])[0];
//            //$introducer_info = Db::name('customer')->where(['user_id'=>$introducer_id])->find();
//
//            //寻找上家
//            //$upHomePeople = $Customer->seekPushPeople($introducer_id,$data['user_id']);
//        }
        unset($data['customer_introducer_name']);

        //申请人
        $applicant = $this->Contract->findUser('customer',['employee_id'=>$data['applicant']]);
        if (empty($applicant)){
            return ['code'=>0,'msg'=>'申请人不存在'];
        }
        if ($applicant['is_entry'] != 1){
            return ['code'=>0,'msg'=>'申请人必须是员工'];
        }
        $data['applicant'] = $applicant['user_id'];

        //判断合同到期时间和换芯时间
        if($data['contract_status']!=6) {
            if ($data['exire_date'] <= time()) {
                $data['is_Expire'] = 1;
            }
            if ($data['for_core_time'] <= time()) {
                $data['is_Core'] = 1;
            }
        }
        //添加操作
//        dump($data);
        Db::startTrans();
        try{
            //添加数据并返回当前ID
            $contract_id = $this->Contract->insertContract($data);
            //添加原始配件
            foreach ($parts as $k=>$v){
                //组装合同ID
                $parts[$k]['contract_id'] = $contract_id;
            }
            $PartsObj->insertAllParts($parts);
            //添加合同操作记录
            $Log = [
                'contract_id'=>$contract_id,
                'do_type'=>1,
                'terminal_type'=>1,
                'new_value'=>'合同，合同编号：'.$data['contract_no'],
            ];
            $this->Contract->addContractLog($Log);
            //添加合同陪住
            $this->Contract->insertContractRemark($remark);
            //添加设备
            foreach ($equipments as $eqkk=>$eqvv){
                $equipments[$eqkk]['contract_id'] = $contract_id;
            }
            $ContractEquipmentObj->insertAllEquipmentsData($equipments);

            //更新直推的设备台数
//            if (!empty($introducer) && isset($introducer_info) && isset($introducer_id)){
//                $num = count($equipments);
//                //转介绍人
//                $introducer_Equipment_number = $introducer_info['number'] + $num;
//                $Customer->updateOne(['user_id'=>$introducer_id],['number'=>$introducer_Equipment_number]);

//                //转介绍人上属单位获得团队推荐台数
//                if (!empty($upHomePeople)){
//                    foreach ($upHomePeople as $upHomePeopleKey=>$upHomePeopleValue){
//                        $where = [
//                            'user_id'=>$upHomePeopleValue['user_id']
//                        ];
//                        $Customer->incTeamEquipmentNumber($where,'team_number',$num);
//                    }
//                }else{
//                    $Customer->incTeamEquipmentNumber(['user_id'=>$introducer_id],'team_number',$num);
//                }
//                //当直推人不是员工时，直推三十台，团队100台，可以入职升级为经销商()
//                if ($introducer_info['is_entry'] != 1){
//                    $entry = Db::name('entry_audit')->where(['user_id'=>$introducer_id])->find();
//                    if ($entry['state'] != 2){
//                        $entry_audit_data = [
//                            'user_id'=>$introducer_id,
//                            'a_id'=>session($this->set['db_name'].'a_id'),
//                            'state'=>1,
//                            'remarks'=>'',
//                            'submit_time'=>time()
//                        ];
//                        //满足30台
//                        if ($introducer_Equipment_number >= 30){
//                            $entry_audit_data['remarks'] = "直推设备满足30台";
//                        }
//                        //满足100台
//                        if ($introducer_info['team_number'] + $num >= 100){
//                            if (!empty($entry_audit_data['remarks'])){
//                                $entry_audit_data['remarks'] .= "和团队设备满足100台";
//                            }else{
//                                $entry_audit_data['remarks'] = "团队设备满足100台";
//                            }
//                        }
//                        Db::name('entry_audit')->insert($entry_audit_data);
//                    }
//
//                }
            //}
            Db::commit();
            return json(array('code'=>1,'msg'=>'新增成功'));
        }catch (\Exception $e){
            echo $e;
            Db::rollback();
            return json(array('code'=>0,'msg'=>'新增失败'));
        }
    }

    /*
     *  修改合同
     *  @author 李港
     */
    public function editContract()
    {
        $contract_id = input('?get.contract_id')?input('get.contract_id'):false;
        if (!$contract_id){
            return ['code'=>0,'msg'=>'非法请求'];
        }
        //获取设备信息
        $ContractEquipmentObj = new ContractEquipment();
        $equipmentsWhere = ['rq_contract_equipment.contract_id'=>$contract_id,'rq_contract_equipment.state'=>1,'rq_contract_equipment.is_delete'=>0];
        $equipmentsJoin = [
            ['rq_equipments','rq_contract_equipment.equipments_id = rq_equipments.equipments_id']
        ];
        $equipmentsField = '
            rq_contract_equipment.id,
            rq_contract_equipment.equipments_id,
            rq_contract_equipment.equipments_number,
            rq_contract_equipment.moving_machine_number,
            rq_equipments.equipments_name
            ';
        $equipments = $ContractEquipmentObj->getEquipmentsData($equipmentsWhere,$equipmentsJoin,$equipmentsField);

        //获取合同信息
        $join = [
            ['rq_customer','rq_contract.user_id = rq_customer.user_id'],
            ['rq_contract_remark','rq_contract_remark.contract_no = rq_contract.contract_no','LEFT']
        ];
        $field = '
            rq_customer.user_id,
            rq_customer.username,
            rq_contract.contract_id,
            rq_contract.introducer_id,
            rq_contract.contract_no,
            rq_contract.contract_money,
            rq_contract.contact_person,
            rq_contract.phone,
            rq_contract.installed_time,
            rq_contract.renew_date,
            rq_contract.for_core_cycle,
            rq_contract.for_core_cost,
            rq_contract.contract_type,
            rq_contract.exire_date,
            rq_contract.eq_count,
            rq_contract.nature,
            rq_contract.corporate_name,
            rq_contract.housing_property,
            rq_contract.original_parts,
            rq_contract.recent_time,
            rq_contract.for_core_time,
            rq_contract.for_core_number,
            rq_contract.moving_machine_number,
            rq_contract.contract_status,
            rq_contract.province_code,
            rq_contract.city_code,
            rq_contract.area_code,
            rq_contract.address,
            rq_contract.contract_imgs,
            rq_contract.applicant,
            rq_contract.receipt,
            rq_contract.is_explain,
            rq_contract.is_special,
            rq_contract.water_pressure,
            rq_contract_remark.remark
            ';
        $contract = $this->Contract->details(['rq_contract.contract_id'=>$contract_id],$join,$field);
        $Customer = new Customer();
        $introducer = $Customer->selectOne(['user_id'=>$contract['introducer_id']]);
        $contract['introducer_telphone'] = $introducer[0]['telphone'];
        $contract['introducer_username'] = $introducer[0]['username'];
        //追加设备信息
        $contract['equipments'] = $equipments;
        //转换图片
        foreach ($contract as $key=>$value){
            if ($key == 'contract_imgs'){
                $contract[$key] = json_decode($value);
                continue;
            }
            if ($key == 'renew_date'){
                continue;
            }
            if (strpos($key,'time') || strpos($key,'date')){
                $contract[$key] = date('Y-m-d',$value);
                continue;
            }
        }
        $PartsObj = new Parts();
        //获取当前合同的原始配件信息
        $contract_parts = $PartsObj->getContractParts(['contract_id'=>$contract_id,'is_delete'=>0]);
        $contract['contract_parts'] = $contract_parts;
        //配件
        $Parts = $PartsObj->getList();
        //设备型号
        $Equipments = new Equipments();
        $equipments_name = $Equipments->getList();
        //显示公司名称
        $is_nature = config('is_nature');
        //客户性质
        $nature = config('nature');
        //住房性质
        $housing_property = config('housing_property');
        //状态
        $contract_status = config('contract_status');
        //判断是否是超级管理员
        $is_admin = session($this->set['db_name'].'is_admin');
        //Operation
        $Operation = new Operation();
        $Province = $Operation->areasProvince();
        $this->assign('Province',$Province);
        $data = [
            'nature'=>$nature,
            'is_nature'=>$is_nature,
            'housing_property'=>$housing_property,
            'equipments_name'=>$equipments_name,
            'Parts'=>$Parts,
            'contract_status'=>$contract_status
        ];

        //申请人
        $applicant = $this->Contract->findUser('customer',['user_id'=>$contract['applicant']]);
        $contract['applicant'] = $applicant['employee_id'];
        $contract['applicant_name'] = $applicant['username'];
        $this->assign('is_admin',$is_admin);
        $City = $Operation->areasCity($contract['province_code']);
        $Area = $Operation->areaName($contract['city_code']);
        $this->assign('City',$City);
        $this->assign('Area',$Area);
        $this->assign('select',$data);
        $this->assign('data',$contract);
        return $this->fetch('contract/edit_contract');
    }

    /*
     *  操作修改合同
     *  @author 李港
     */
    public function doEditContract()
    {
        $data = $this->request->post();
        foreach ($data as $key => $value){
            if ($key == 'renew_date'){
                continue;
            }
            //转化时间
            if (strpos($key,'time') || strpos($key,'date')){
                if (!empty($value)){
                    $data[$key] = strtotime($value);
                    continue;
                }
            }

            //去掉空格
            if (!is_array($value)){
                $data[$key] = trim($value);
                continue;
            }
        }
        //检查是否为空
        $msg = '';
        foreach ($data as $emk=>$emv){
            //判断基本信息
            if (!is_array($emv)){
                if (strlen($emv) == 0){
                    switch ($emk){
                        case 'user_id':
                            $msg = '用户';
                            break;
                        case 'introducer_id':
                            $msg = '转介绍人';
                            break;
                        case 'contract_no':
                            $msg = '合同编号';
                            break;
                        case 'contract_money':
                            $msg = '合同金额';
                            break;
                        case 'contact_person':
                            $msg = '联系人';
                            break;
                        case 'installed_time':
                            $msg = '装机时间';
                            break;
                        case 'phone':
                            $msg = '联系电话';
                            break;
                        case 'renew_date':
                            $msg = '续费周期';
                            break;
                        case 'for_core_cycle':
                            $msg = '用户';
                            break;
                        case 'nature':
                            $msg = '客户性质';
                            break;
                        case 'housing_property':
                            $msg = '住房性质';
                            break;
                        case 'recent_time':
                            $msg = '最近一次换芯时间';
                            break;
                        case 'for_core_time':
                            $msg = '换芯时间';
                            break;
                        case 'for_core_number':
                            $msg = '免费换芯次数';
                            break;
                        case 'moving_machine_number':
                            $msg = '用户';
                            break;
                        case 'exire_date':
                            $msg = '到期时间';
                            break;
                        case 'contract_status':
                            $msg = '账户状态';
                            break;
                        case 'province_code':
                            $msg = '省';
                            break;
                        case 'city_code':
                            $msg = '市';
                            break;
                        case 'area_code':
                            $msg = '区/县';
                            break;
                        case 'address':
                            $msg = '详细地址';
                            break;
                        case 'applicant':
                            $msg = '申请人';
                            break;
                        case 'receipt':
                            $msg = '收据编号';
                            break;
                        case 'water_pressure':
                            $msg = '水压';
                            break;
                        default:
                            $msg='';
                    }
                }
            }else{
                //判断设备
                if ($emk == 'equipments_number'){
                    foreach ($emv as $cheqk=>$cheqv){
                        if (empty($cheqv)){
                            $msg = '设备编号';
                             break;
                        }
                    }
                }
                if (empty($emv) && $emk == 'equipments_name'){
                    $msg = '装机型号';
                    break;
                }
            }
        }
        if (!empty($msg)){
            return ['code'=>0,'msg'=>$msg.'不能为空'];
        }
        //组装设备数据
        $equipments = [];
        foreach ($data['equipments_number'] as $numberK=>$numberV){
            foreach ($data['equipments_name'] as $nameK=>$nameV){
                foreach ($data['id'] as $idk=>$idv){
                    if ($numberK == $nameK && $idk == $numberK && $idk == $nameK && !empty($idv)) {
                        //修改
                        $equipments[$nameK]['id'] = $idv;
                        $equipments[$nameK]['contract_id'] = $data['contract_id'];
                        $equipments[$nameK]['equipments_number'] = $numberV;
                        $equipments[$nameK]['equipments_id'] = $nameV;
                        $equipments[$nameK]['equipments_address'] = $data['address'];
                        $equipments[$nameK]['moving_machine_number'] = $data['moving_machine_number'][$nameK]?$data['moving_machine_number'][$nameK]:1;
                        $equipments[$nameK]['uptime'] = time();
                        continue;
                    }else{
                        //添加
                        if ($numberK == $nameK) {
                            $equipments[$nameK]['contract_id'] = $data['contract_id'];
                            $equipments[$nameK]['equipments_number'] = $numberV;
                            $equipments[$nameK]['equipments_id'] = $nameV;
                            $equipments[$nameK]['equipments_address'] = $data['address'];
                            $equipments[$nameK]['moving_machine_number'] = $data['moving_machine_number'][$nameK]?$data['moving_machine_number'][$nameK]:1;
                            $equipments[$nameK]['addtime'] = time();
                            $equipments[$nameK]['uptime'] = time();
                            continue;
                        }
                    }
                }
            }
        }
        //区分添加修改设备
        $updateEquipments = [];//更新的设备
        $addEquipments = [];//添加的设备
        foreach ($equipments as $kkk=>$vvv){
            if (in_array('id',array_keys($vvv))){
                array_push($updateEquipments,$vvv);
            }else{
                array_push($addEquipments,$vvv);
            }
        }
        //实例化合同设备关联model
        $ContractEquipmentObj = new ContractEquipment();

        //去掉合同中的设备信息
        unset($data['equipments_number']);
        unset($data['equipments_name']);

        $data['moving_machine_number'] = $data['contract_moving_machine_number'];
        unset($data['contract_moving_machine_number']);

        //获取省市区
        $data['province'] = $this->Operation->findAddrName(['id'=>$data['province_code']])[0]['area_name'];
        $data['city'] = $this->Operation->findAddrName(['id'=>$data['city_code']])[0]['area_name'];
        $data['area'] = $this->Operation->findAddrName(['id'=>$data['area_code']])[0]['area_name'];

        //合同备注
        $remark['remark'] = $data['remark'];
        $remark['add_time'] = time();
        $remark['contract_no'] = $data['contract_no'];


        unset($data['engineers_name']);
        unset($data['remark']);
        unset($data['id']);

        //组装记录信息
        //新增设备
        $addEquipmentsLog = [
            'contract_id'=>$data['contract_id'],
            'do_type'=>1,
            'terminal_type'=>1,
            'old_value'=>'',
            'new_value'=>''
        ];
        /*
        //新增原始配件
        $addPartsLog = [
            'contract_id'=>$data['contract_id'],
            'do_type'=>1,
            'terminal_type'=>1,
            'old_value'=>'',
            'new_value'=>''
        ];
        */
        //新增图片
        $addImgsLog = [
            'contract_id'=>$data['contract_id'],
            'do_type'=>1,
            'terminal_type'=>1,
            'old_value'=>'',
            'new_value'=>''
        ];
        //删除
        $deleteLog = [
            'contract_id'=>$data['contract_id'],
            'do_type'=>2,
            'terminal_type'=>1,
            'old_value'=>'',
            'new_value'=>''
        ];
        //编辑
        $updateLog = [
            'contract_id'=>$data['contract_id'],
            'do_type'=>3,
            'terminal_type'=>1,
            'old_value'=>'',
            'new_value'=>''
        ];


        //检查设备变更信息
        //------------------------Start------------------------------------
        $AllEquipmentsWhere = [
            'contract_id'=>$data['contract_id'],
            'rq_contract_equipment.state'=>1,
            'rq_contract_equipment.is_delete'=>0
        ];
        $AllEquipmentsJoin = [
            ['rq_equipments','rq_contract_equipment.equipments_id=rq_equipments.equipments_id']
        ];
        $AllEquipmentsField = '
                rq_contract_equipment.id,
                rq_contract_equipment.equipments_id,
                rq_equipments.equipments_name,
                rq_contract_equipment.equipments_number,
                rq_contract_equipment.moving_machine_number
            ';
        $oldEquipmentsInfoAll = $ContractEquipmentObj->getEquipmentsData($AllEquipmentsWhere,$AllEquipmentsJoin,$AllEquipmentsField);

        //添加设备的记录
        foreach ($addEquipments as $addK=>$addV){
            $addEquipmentsLog['new_value'] .= '设备编号：'.$addV['equipments_number'].';';
        }
        //修改设备的记录
        $ueJoin = [
            ['rq_equipments','rq_contract_equipment.equipments_id=rq_equipments.equipments_id']
        ];
        $ueField = '
                rq_contract_equipment.id,
                rq_equipments.equipments_name,
                rq_contract_equipment.equipments_id,
                rq_contract_equipment.equipments_number,
                rq_contract_equipment.moving_machine_number
            ';
        foreach ($updateEquipments as $uek=>$uev){
            $ueWhere = [
                'rq_contract_equipment.id'=>$uev['id'],
                'rq_contract_equipment.state'=>1,
                'rq_contract_equipment.is_delete'=>0
            ];
            //删除设备
            if (count($oldEquipmentsInfoAll) != count($updateEquipments)){
                foreach ($oldEquipmentsInfoAll as $oeiaK=>$oeiaV){
                    if ($oeiaV['id'] == $uev['id']){
                        $deleteEquipmentsKey[] = $oeiaK;
                    }
                }
            }

            //修改设备
            $oldEquipmentsInfo = $ContractEquipmentObj->getEquipmentsData($ueWhere,$ueJoin,$ueField)[0];
//            $newEquipmentsInfo = $ContractEquipmentObj->getEquipmentsData(['rq_equipments.equipments_id'=>$uev['equipments_id']],$ueJoin,$ueField)[0];
            $newEquipmentsInfo = Db::table('rq_equipments')->where(['rq_equipments.equipments_id'=>$uev['equipments_id']])->find();

            if ($oldEquipmentsInfo['equipments_name'] != $newEquipmentsInfo['equipments_name']){
                $updateLog['old_value'] .= '设备型号：'.$oldEquipmentsInfo['equipments_name'].';';
                $updateLog['new_value'] .= '设备型号：'.$newEquipmentsInfo['equipments_name'].';';
            }
            if ($oldEquipmentsInfo['equipments_number'] != $uev['equipments_number']){
                $updateLog['old_value'] .= '设备编号：'.$oldEquipmentsInfo['equipments_number'].';';
                $updateLog['new_value'] .= '设备编号：'.$uev['equipments_number'].';';
            }
            if ($oldEquipmentsInfo['moving_machine_number'] != $uev['moving_machine_number']){
                $updateLog['old_value'] .= '设备移机次数：'.$oldEquipmentsInfo['moving_machine_number'].';';
                $updateLog['new_value'] .= '设备移机次数：'.$uev['moving_machine_number'].';';
            }
        }

        //删除的设备LOG
        if (isset($deleteEquipmentsKey)){
            foreach ($deleteEquipmentsKey as $deK=>$dev){
                unset($oldEquipmentsInfoAll[$dev]);
            }
            foreach ($oldEquipmentsInfoAll as $delK=>$delV){
                $deleteLog['old_value'] = "设备编号：".$delV['equipments_number'].';';
            }
        }else{
            $oldEquipmentsInfoAll = [];
        }
        //------------------------End------------------------------------

        //图片修改记录
        //图片操作
        if (!isset($data['contract_imgs']) && empty($data['contract_imgs'])){
            return ['code'=>0,'msg'=>'请上传图片'];
        }
        $oldImgs = $this->Contract->details(['contract_id'=>$data['contract_id']],[],'contract_imgs');
        $oldImgsArray = json_decode($oldImgs['contract_imgs']);
        //删除
        if (!empty($oldImgsArray)){
            foreach ($oldImgsArray as $ImgK=>$ImgV){
                if (!in_array($ImgV, $data['contract_imgs'])) {
                    $deleteLog['old_value'] .= '合同图片：' . $ImgV . ';';
                }
            }
        }

        //添加
        foreach ($data['contract_imgs'] as $ImgNewK=>$ImgNewV) {
            if (!empty($oldImgsArray)){
                if (!in_array($ImgNewV, $oldImgsArray)) {
                    $addImgsLog['new_value'] .= '合同图片：' . $ImgNewV . ';';
                }
            }else{
                $addImgsLog['new_value'] .= '合同图片：' . $ImgNewV . ';';
            }

        }
        $data['contract_imgs'] = json_encode($data['contract_imgs']);
        $data['update_time'] = time();

        //判断合同到期时间和换芯时间
        if($data['contract_status']!=6) {
            if ($data['exire_date'] <= time()) {
                $data['is_Expire'] = 1;
            } else {
                $data['is_Expire'] = 0;
            }
            if ($data['for_core_time'] <= time()) {
                $data['is_Core'] = 1;
            } else {
                $data['is_Core'] = 0;
            }
        }
        //转介绍人
        if(!empty($data['customer_introducer_name'])) {
            $introducer = $data['customer_introducer_name'];
            $res = db('contract')->where('contract_no', $introducer)->find();
            if ($res) {
                $data['introducer_id'] = $res['user_id'];
            } else {
                return ['code' => 0, 'msg' => '转介绍人合同不存在'];
            }
        }else{
            $data['introducer_id'] = '';
        }
        unset($data['customer_introducer_name']);

        //申请人
        $applicant = $this->Contract->findUser('customer',['employee_id'=>$data['applicant']]);
        if (empty($applicant)){
            return ['code'=>0,'msg'=>'申请人不存在'];
        }
        if ($applicant['is_entry'] != 1){
            return ['code'=>0,'msg'=>'申请人必须是员工'];
        }
        $data['applicant'] = $applicant['user_id'];

        //判断修改合同编号
        if ($data['contract_no'] != $data['hidden_contract_no']){
            $check_contract_no = Db::table('rq_contract')->where(['contract_no'=>$data['contract_no']])->find();
            if (!empty($check_contract_no)){
                return ['code'=>0,'msg'=>'合同编号已经存在'];
            }
        }
        unset($data['hidden_contract_no']);


        //入库
        Db::startTrans();
        try{
            //添加数据并返回当前ID
            $this->Contract->updateContract([],$data);
            $this->Contract->updateContractRemark(['contract_no'=>$data['contract_no']],$remark);
            //添加设备
            if ($addEquipments){
                foreach ($addEquipments as $addk=>$addv){
                    $ContractEquipmentObj->insertEquipmentsData($addv);
                    $addEquipmentsLog['new_value'] = '设备编号：'.$addv['equipments_number'];
                    $this->Contract->addContractLog($addEquipmentsLog);
                }
            }
            //更新设备
            if ($updateEquipments){
                foreach ($updateEquipments as $updk=>$updv){
                    $ContractEquipmentObj->updateEquipmentsData([],$updv);
                }
            }
            //删除设备
            if ($oldEquipmentsInfoAll){
                foreach ($oldEquipmentsInfoAll as $delk=>$delv){
                    $delData = [
                        'id'=>$delv['id'],
                        'is_delete'=>1,
                        'state'=>0
                    ];
                    $ContractEquipmentObj->updateEquipmentsData([],$delData);
                }
            }
            //添加图片
            if ($addImgsLog['new_value']){
                $this->Contract->addContractLog($addImgsLog);
            }
            //删除
            if ($deleteLog['old_value']){
                $this->Contract->addContractLog($deleteLog);
            }
            Db::commit();
            return json(array('code'=>1,'msg'=>'编辑成功'));
        }catch (\Exception $e){
            echo $e;
            Db::rollback();
            return json(array('code'=>0,'msg'=>'编辑失败'));
        }
    }

    /*
     *  获取用户
     */
    public function getCustomer()
    {
        $susername = input('susername');
        $stelphone = input('stelphone');
        $sid_card = input('sid_card');
        if(trim($susername)){
            $where['username'] = $susername;
        }
        if(trim($stelphone)){
            $where['telphone'] = $stelphone;
        }
        if(trim($sid_card)){
            $where['id_card'] = $sid_card;
        }
        $Customer = new Customer();
        $a_id = session($this->set['db_name'].'a_id');
        $where['administrative_id'] = $a_id;
        $where['page'] = input('page');
        $result = $Customer->selectPage($where);
        return json($result);
    }

    /*
     *  获取设备编号
     *  @return json    设备编号
     */
    public function getEquipmentsNumber()
    {
        $EquipmentsNumber = randEquipmentsNumber();
        return  json($EquipmentsNumber);
    }

    /*
     * 上传图片
     * @author  李港
     */
    public function uploadFile()
    {
        $file = request()->file('avatar_img');
        //移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'contract');
        if($info){
            return ['code'=>1,'data'=>$info->getSaveName()];
        }else{
            return ['code'=>1,'msg'=>'图片上传失败'];
        }

    }

    /**
     * 根据省获取市
     * @author ligang
     * @Request province             int    GET   省ID
     * @return array|bool
     */
    public function selectCity()
    {
        $province_id = '';
        if(input('?get.province') && !empty(input('get.province'))) {
            $province_id = input('get.province');
        }
        $City = $this->Operation->areasCity($province_id);
        return json($City);
    }

    /**
     * 根据市获取区县
     * @author ligang
     * @Request province             int    GET   省ID
     * @return array
     */
    public function selectArea()
    {
        $City_id = '';
        if(input('?get.city') && !empty(input('get.city'))) {
            $City_id = input('get.city/d');
        }else{
            return array();
        }
        $City = $this->Operation->areaName($City_id);
        return json($City);
    }

    /**
     * 合同关系导出
     */
    public function export()
    {
        ini_set("max_execution_time", "0");
        ob_end_clean();//清除缓冲区,避免乱码
        ob_start();
        header('Content-Type:text/html;charset=utf-8');
        $aid = session($this->set['db_name'].'a_id');
        $where=[
            'rq_contract.is_delete'=>0,
            'administrative_id'=>$aid,
        ];
        $start_time = input('get.start_time');
        $end_time = input('get.end_time');
        if (!empty($start_time)){
            if (!empty($end_time)){
                $where['installed_time'] = ['BETWEEN',[strtotime(date('Y-m-d 00:00:00',strtotime($start_time))),strtotime(date('Y-m-d 23:59:59',strtotime($end_time)))]];
            }else{
                $where['installed_time'] = ['BETWEEN',[strtotime(date('Y-m-d 00:00:00',strtotime($start_time))),strtotime(date('Y-m-d 23:59:59',time()))]];
            }
        }else{
            if (!empty($end_time)){
                $where['installed_time'] = ['BETWEEN',[strtotime(date('Y-m-d 00:00:00',time())),strtotime(date('Y-m-d 23:59:59',strtotime($end_time)))]];
            }
        }

        /*
        $rank=db('contract_rank')->alias('a')
            ->join('contract at', 'a.contract_no=at.contract_no','left')
            ->where($where)
            ->field('
                a.*,at.contract_money,at.phone,at.contact_person,at.corporate_name,at.installed_time,
                at.address,at.province,at.city,at.area,at.installed_time,contract_status,at.housing_property,
                at.nature,at.user_id
            ')
            ->select();
        foreach ($rank as $k=>$v){
            $rank[$k]['equipment']=db('contract_equipment')->alias('a')
                ->join('equipments at','a.equipments_id=at.equipments_id','left')
                ->value('equipments_name');
            $rank[$k]['type']=(db('customer')->where(array('user_id'=>$v['user_id']))
                ->value('user_type')==1)?'普通客户':'VIP客户';
            $rank[$k]['installed_time']=date('Y-m-d',$v['installed_time']);
            $rank[$k]['name']=($v['corporate_name']==null)?(($v['contact_person']==null)?'':$v['contact_person']):$v['corporate_name'];
            unset($rank[$k]['contact_person']);
            unset($rank[$k]['corporate_name']);
            switch ($v['contract_status']){//1.正常,2.拆机冻结,3.退机冻结,4.合同到期停止服务,5.拒绝付费停止服务,6.买断停止服务，7无效
                case 1: $rank[$k]['contract_status']='正常';
                    break;
                case 2:$rank[$k]['contract_status']='拆机冻结';
                    break;
                case 3:$rank[$k]['contract_status']='退机冻结';
                    break;
                case 4:$rank[$k]['contract_status']='合同到期停止服务';
                    break;
                case 5:$rank[$k]['contract_status']='拒绝付费停止服务';
                    break;
                case 6:$rank[$k]['contract_status']='买断停止服务';
                    break;
                case 7:$rank[$k]['contract_status']='无效';
                    break;
            }
            switch ($v['nature']){//客户性质(1.商用客户,2.家用客户,3外接包年,4.外接点餐,5.购买客户)'
                case 1: $rank[$k]['nature']='商用客户';
                    break;
                case 2:$rank[$k]['nature']='家用客户';
                    break;
                case 3:$rank[$k]['nature']='外接包年';
                    break;
                case 4:$rank[$k]['nature']='外接点餐';
                    break;
                case 5:$rank[$k]['nature']='购买客户';
                    break;
            }
            switch ($v['housing_property']){//住房性质(1.公租房,2.廉租房,3.租赁,4.购买)
                case 1: $rank[$k]['housing_property']='公租房';
                    break;
                case 2:$rank[$k]['housing_property']='廉租房';
                    break;
                case 3:$rank[$k]['housing_property']='租赁';
                    break;
                case 4:$rank[$k]['housing_property']='购买';
                    break;
            }
        }
        */
        $join = [
            ['rq_customer','rq_contract.user_id = rq_customer.user_id','LEFT'],
            ['rq_contract_remark','rq_contract.contract_no = rq_contract_remark.contract_no','LEFT']
        ];
        $field = '  rq_contract.phone,
                    rq_contract.contract_id,
                    rq_contract.contact_person,
                    rq_contract.corporate_name,
                    rq_contract.contract_no,
                    rq_contract.address,
                    rq_contract.installed_time,
                    rq_contract.contract_status,
                    rq_contract.housing_property,
                    rq_contract.province,
                    rq_contract.city,
                    rq_contract.area,
                    rq_contract.contract_type,
                    rq_contract.introducer_id,
                    rq_contract.applicant,
                    rq_contract.for_core_cost,
                    rq_customer.username,
                    rq_customer.user_type,
                    rq_contract_remark.remark,
                    rq_contract.nature';
        $data = Db::table('rq_contract')->where($where)->field($field)->join($join)->select();

        $e_join = [
            ['rq_equipments','rq_contract_equipment.equipments_id = rq_equipments.equipments_id','LEFT']
        ];
        $e_field = 'rq_equipments.equipments_name';
        $e_where = [
            'state'=>1,
            'rq_contract_equipment.is_delete'=>0
        ];
        foreach ($data as $key=>$value){
            if (!empty($value['introducer_id'])){
                $data[$key]['introducer_name'] = Db::table('rq_customer')->where(['user_id'=>$value['introducer_id']])->field('username')->find()['username'];
            }else{
                $data[$key]['introducer_name'] = '';
            }

            if (!empty($value['applicant'])){
                $data[$key]['applicant_name'] = Db::table('rq_customer')->where(['user_id'=>$value['applicant']])->field('username')->find()['username'];
            }else{
                $data[$key]['applicant_name'] = '';
            }

            $data[$key]['installed_time'] = date('Y-m-d',$value['installed_time']);
            switch ($value['contract_status']){//1.正常,2.拆机冻结,3.退机冻结,4.合同到期停止服务,5.拒绝付费停止服务,6.买断停止服务，7无效
                case 1: $data[$key]['contract_status']='正常';
                    break;
                case 2:$data[$key]['contract_status']='拆机冻结';
                    break;
                case 3:$data[$key]['contract_status']='退机冻结';
                    break;
                case 4:$data[$key]['contract_status']='合同到期停止服务';
                    break;
                case 5:$data[$key]['contract_status']='拒绝付费停止服务';
                    break;
                case 6:$data[$key]['contract_status']='买断停止服务';
                    break;
                case 7:$data[$key]['contract_status']='无效';
                    break;
            }
            switch ($value['nature']){//客户性质(1.商用客户,2.家用客户,3外接包年,4.外接点餐,5.购买客户)'
                case 1: $data[$key]['nature']='商用客户';
                    $data[$key]['contact_person'] = $value['corporate_name'];
                    break;
                case 2:$data[$key]['nature']='家用客户';
                    break;
                case 3:$data[$key]['nature']='外接包年';
                    break;
                case 4:$data[$key]['nature']='外接点餐';
                    break;
                case 5:$data[$key]['nature']='购买客户';
                    break;
            }
            switch ($value['housing_property']){//住房性质(1.公租房,2.廉租房,3.租赁,4.购买)
                case 1: $data[$key]['housing_property']='公租房';
                    break;
                case 2:$data[$key]['housing_property']='廉租房';
                    break;
                case 3:$data[$key]['housing_property']='租赁';
                    break;
                case 4:$data[$key]['housing_property']='购买';
                    break;
            }

            $data[$key]['contract_type'] = $value['contract_type'] ? '是' : '否';

            $data[$key]['equipment'] = '';
            $e_where['contract_id'] = $value['contract_id'];
            $equipment = Db::table('rq_contract_equipment')->where($e_where)->join($e_join)->field($e_field)->select();
            foreach ($equipment as $k=>$v){
                $data[$key]['equipment'] .= $v['equipments_name'] . ',';
            }
            $data[$key]['equipment'] = substr($data[$key]['equipment'],0,-1);
        }
        $this->exportExcel($data,$where);
    }

    public function exportExcel($data,$where){
        if (!is_array($data)) {
            return "数据格式错误";
        }
        $title = '';
        if (isset($where['installed_time']) && !empty($where['installed_time'])){
            $title .= date('Y-m-d H:i:s',$where['installed_time'][1][0]);
            $title .= ' 至 ';
            $title .= date('Y-m-d H:i:s',$where['installed_time'][1][1]);
        }
        $title .= ' 合同信息';
        $filename = '合同信息' . '-' . date('Y-m-d H:i:s', time()) . ".xls";
        Vendor('phpexcel.phpexcel.Classes.PHPExcel');
        $PHPExcel = new \PHPExcel();
	
        //设置信任
        $PHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        //设置标题
        $PHPExcel->getActiveSheet()->setCellValue('A1',$title);
        $PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(35);
        $PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(22);
        $PHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(20);
        //合并单元格
        $PHPExcel->getActiveSheet()->mergeCells('A1:M1');
        //设置列宽
        $PHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
        $PHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
        $PHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(30);
        //设置表头
        $PHPExcel->getActiveSheet()->setCellValue('A2', '姓名');
        $PHPExcel->getActiveSheet()->setCellValue('B2', '联系电话');
        $PHPExcel->getActiveSheet()->setCellValue('C2', '合同编号');
        $PHPExcel->getActiveSheet()->setCellValue('D2', '机型');
        $PHPExcel->getActiveSheet()->setCellValue('E2', '装机地址');
        $PHPExcel->getActiveSheet()->setCellValue('F2', '合同状态');
        $PHPExcel->getActiveSheet()->setCellValue('G2', '房屋类型');
        $PHPExcel->getActiveSheet()->setCellValue('H2', '是否升级VIP');
        $PHPExcel->getActiveSheet()->setCellValue('I2', '准经销商');
        $PHPExcel->getActiveSheet()->setCellValue('J2', '转介绍');
        $PHPExcel->getActiveSheet()->setCellValue('K2', '装机时间');
        $PHPExcel->getActiveSheet()->setCellValue('L2', '服务金额');
        $PHPExcel->getActiveSheet()->setCellValue('M2', '合同备注');
        //设置字体样式
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        $PHPExcel->getActiveSheet()->getStyle('A2:M2')->getFont()->setName('微软雅黑');
        $PHPExcel->getActiveSheet()->getStyle('A2:M2')->getFont()->setSize(14);
        $PHPExcel->getActiveSheet()->getStyle('A2:M2')->getFont()->setBold(true);
        $PHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        foreach ($data as $k => $v) {
            //设置单元格值
            $PHPExcel->getActiveSheet()->setCellValue('A' . ($k + 3), $v['username']);
            $PHPExcel->getActiveSheet()->setCellValue('B' . ($k + 3), ' '.$v["phone"]);
            $PHPExcel->getActiveSheet()->setCellValue('C' . ($k + 3), ' '.$v["contract_no"]);
            $PHPExcel->getActiveSheet()->setCellValue('D' . ($k + 3), $v['equipment']);
            $PHPExcel->getActiveSheet()->setCellValue('E' . ($k + 3), $v['province'] . $v['city'] . $v['area'] . $v['address']);
            $PHPExcel->getActiveSheet()->setCellValue('F' . ($k + 3), $v['contract_status']);
            $PHPExcel->getActiveSheet()->setCellValue('G' . ($k + 3), $v['housing_property']);
            $PHPExcel->getActiveSheet()->setCellValue('H' . ($k + 3), $v['contract_type']);
            $PHPExcel->getActiveSheet()->setCellValue('I' . ($k + 3), $v['applicant_name']);
            $PHPExcel->getActiveSheet()->setCellValue('J' . ($k + 3), $v['introducer_name']);
            $PHPExcel->getActiveSheet()->setCellValue('K' . ($k + 3), $v['installed_time']);
            $PHPExcel->getActiveSheet()->setCellValue('L' . ($k + 3), $v['for_core_cost'] . '元');
            $PHPExcel->getActiveSheet()->setCellValue('M' . ($k + 3), $v['remark']);
            //设置居中
            $PHPExcel->getActiveSheet()->getStyle('A2:M' . ($k + 3))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            //垂直居中
            $PHPExcel->getActiveSheet()->getStyle('A' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('B' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('C' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('D' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('E' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('F' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('G' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('H' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('I' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('J' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('K' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('L' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('M' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        }
        $PHPSheet = $PHPExcel->getActiveSheet();
        //给当前活动sheet设置名称
        $PHPSheet->setTitle("合同信息");
		
        //创建生成的格式
        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel5");
		
        //下载下来的表格名
        ob_end_clean();
        header('content-Type:application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Cache-Control: max-age=0');
		try{
				$PHPWriter->save("php://output");
		}catch(Exception $e){
			var_dump($e);exit;
		}
        


    }

}